package com.fenyin.samples.study.netty.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileUtil {
	
//	public static String readFile(String filePathAndName) { 
//		   StringBuffer data = new StringBuffer();
//		   try {  
//		    File f = new File(filePathAndName); 
//		    if(f.isFile()&&f.exists()){ 
//		     InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8"); 
//		     BufferedReader reader=new BufferedReader(read); 
//		     String line; 
//		     while ((line = reader.readLine()) != null) { 
//		      data.append(line).append("\n");
////		      data.append(line).append("\n\r");
//		     }   
//		     read.close(); 
//		    } 
//		   } catch (Exception e) { 
//		    System.out.println("读取文件内容操作出错"); 
//		    e.printStackTrace(); 
//		   } 
//		   return data.toString(); 
//		} 
	
	public static String readFile(String filePath){
		FileInputStream input = null;
		byte[] buffer = new byte[5512];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		File file = new File(filePath);
		if(!file.exists()){
			throw new IllegalArgumentException("文件路径不存在");
		}
		try{
			input = new FileInputStream(file);
			int offset = 0;
			while((offset=input.read(buffer)) != -1){
				out.write(buffer, 0, offset);
			}
			return new String(out.toByteArray(),"UTF-8");
		}catch(Throwable th){
			throw new IllegalStateException("文件操作异常",th);
		}finally{
			if(input!=null){
				try {
					input.close();
				} catch (IOException e) {
					throw new IllegalStateException("流关闭异常",e);
				}
			}
			
			if(out !=null){
				try {
					out.close();
				} catch (IOException e) {
					throw new IllegalStateException("流关闭异常",e);
				}
			}
		}
	}
	
	public static void main(String[] args){
		System.out.println(readFile("D:\\temp\\homepage"));
	}
}
